package com.example.pre.controller;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.pre.business.LoginBusiness;
import com.example.pre.controller.base.ControllerBase;
import com.example.pre.enums.UserTypeEnum;
import com.example.pre.exception.ExceptionMessage;
import com.example.pre.exception.ExtParaException;
import com.example.pre.exception.ServiceException;
import com.example.pre.interceptor.LoginFreeBlocking;
import com.example.pre.model.User;
import com.example.pre.tools.StringUtils;
import com.example.pre.tools.TokenTools;
import com.example.pre.tools.Tools;

/*
 * 登录controller层接口
 */
@RestController
public class LoginController extends ControllerBase {

	private final Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private LoginBusiness loginBusiness;

	/**
	 * 管理员登录
	 * 
	 * @param account  账号
	 * @param password 密码
	 * @return
	 */
	@LoginFreeBlocking
	@RequestMapping(value = "/administrator/login", method = RequestMethod.POST)
	public Map<String, Object> adminLogin(@RequestParam String account, @RequestParam String password) {
		// 获取响应开始时间
		long start = System.currentTimeMillis();
		// 使用UUID做eventId
		String eventId = Tools.createUUID();
		String inputPara = ",传入的参数为account=" + account + ",password=" + password;
		String message = "";
		// 预创建返回值
		HashMap<String, Object> result = new HashMap<String, Object>();
		result.put("flag", false);
		result.put("message", "OK");
		result.put("code", 0);
		result.put("data", null);
		try {
			// 字段验证
			if (StringUtils.isEmpty(account)) {
				result.put("message", "管理员账号为空，登录失败");
				result.put("code", -501);
				message = "管理员登录时，账号为空";
				logger.error(super.createLog(new Exception(), message + inputPara, start, eventId));
				return result;
			}
			if (StringUtils.isEmpty(password)) {
				result.put("message", "密码为空，登录失败");
				result.put("code", -501);
				message = "管理员登录时，密码为空";
				logger.error(super.createLog(new Exception(), message + inputPara, start, eventId));
				return result;
			}
			// 管理员登录，成功直接返回true
			loginBusiness.adminLogin(account, password);
			return result;
		} catch (ServiceException e) {
			ExceptionMessage exceptionMessage = e.getExceptionMessage();
			int code = exceptionMessage.getCode();
			result.put("code", code);
			result.put("message", exceptionMessage.getShowMessage());
			message = "管理员登录取时，业务报错：" + exceptionMessage.getLogMessage();
			logger.error(super.createLog(e, message + inputPara, start, eventId));
			return result;
		} catch (ExtParaException e) {
			ExceptionMessage exceptionMessage = e.getExceptionMessage();
			int code = exceptionMessage.getCode();
			result.put("code", code);
			result.put("message", exceptionMessage.getShowMessage());
			message = "管理员登录取时，第三方业务报错：" + exceptionMessage.getLogMessage();
			logger.error(super.createLog(e, message + inputPara, start, eventId));
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", -400);
			result.put("message", "系统繁忙，请稍后重试");
			message = "管理员登录取时，系统报错：" + e.getMessage();
			logger.error(super.createLog(e, message + inputPara, start, eventId));
			return result;
		}
	}

	/**
	 * 用户登录
	 * 
	 * @param account  账号
	 * @param password 密码
	 * @return
	 */
	@LoginFreeBlocking
	@RequestMapping(value = "/user/login", method = RequestMethod.POST)
	public Map<String, Object> userLogin(@RequestParam String account, @RequestParam String password) {
		// 获取响应开始时间
		long start = System.currentTimeMillis();
		// 使用UUID做eventId
		String eventId = Tools.createUUID();
		String inputPara = ",传入的参数为account=" + account + ",password=" + password;
		String message = "";
		// 预创建返回值
		HashMap<String, Object> result = new HashMap<String, Object>();
		result.put("flag", false);
		result.put("message", "OK");
		result.put("code", 0);
		result.put("data", null);
		try {
			// 字段验证
			if (StringUtils.isEmpty(account)) {
				result.put("message", "用户账号为空，登录失败");
				result.put("code", -501);
				message = "管理员登录时，账号为空";
				logger.error(super.createLog(new Exception(), message + inputPara, start, eventId));
				return result;
			}
			if (StringUtils.isEmpty(password)) {
				result.put("message", "密码为空，登录失败");
				result.put("code", -501);
				message = "用户登录时，密码为空";
				logger.error(super.createLog(new Exception(), message + inputPara, start, eventId));
				return result;
			}
			String loginKey = this.createLoginKey();
			User userLogin = loginBusiness.userLogin(account, password);
			if (userLogin != null) {
				result.put("flag", true);
				result.put("data", userLogin);
				message = "用户登录成功";
				result.put("message", message);
				this.setToken(UserTypeEnum.user.name(), account, userLogin.getId(),
						Tools.encryptBASE64(password.getBytes()), loginKey);
				userLogin.setPassword("******");
				logger.info(super.createLog(message + inputPara, start, eventId));
			} else {
				message = "用户登录失败";
				result.put("message", message);
				logger.error(super.createLog(new Exception(), message + inputPara, start, eventId));
			}
			return result;
		} catch (ServiceException e) {
			ExceptionMessage exceptionMessage = e.getExceptionMessage();
			int code = exceptionMessage.getCode();
			result.put("code", code);
			result.put("message", exceptionMessage.getShowMessage());
			message = "用户登录取时，业务报错：" + exceptionMessage.getLogMessage();
			logger.error(super.createLog(e, message + inputPara, start, eventId));
			return result;
		} catch (ExtParaException e) {
			ExceptionMessage exceptionMessage = e.getExceptionMessage();
			int code = exceptionMessage.getCode();
			result.put("code", code);
			result.put("message", exceptionMessage.getShowMessage());
			message = "用户登录取时，第三方业务报错：" + exceptionMessage.getLogMessage();
			logger.error(super.createLog(e, message + inputPara, start, eventId));
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", -400);
			result.put("message", "系统繁忙，请稍后重试");
			message = "用户登录取时，系统报错：" + e.getMessage();
			logger.error(super.createLog(e, message + inputPara, start, eventId));
			return result;
		}
	}

	/**
	 * 给登录用户设置token
	 *
	 * @param userType       用户类型
	 * @param userIdentityId 用户账号
	 * @param userId         用户ID
	 * @param loginKey       登录标识
	 * @throws Exception
	 */
	private void setToken(String userType, String account, int userId, String pwd, String loginKey) throws Exception {
		String newPwd = StringUtils.isEmpty(pwd) ? Tools.encryptBASE64(account.getBytes()) : pwd;
		this.response.setHeader("Authorization", TokenTools.createToken(userType, account, userId, newPwd, loginKey));
		this.response.setHeader("User-Type", userType);
		this.response.setIntHeader("User-Id", userId);
		this.response.setHeader("User-Number", account);
	}

	/**
	 * 生成LoginKey
	 * 
	 * @return LoginKey
	 */
	private String createLoginKey() {
		return Tools.createUUID() + System.currentTimeMillis();
	}

}
